<template>
    <div class="layout">
        <div class="container">
            <div class="container_right">
                <el-tabs v-model="searchType" @tab-change="handleTabChange">
                    <el-tab-pane label="按员工" name="wokerUser" />
                    <el-tab-pane label="按群聊" name="groupChat" />
                    <el-tab-pane label="按日期" name="date" />
                </el-tabs>
                <ZwSearchForm
                    row-num="4"
                    :option="searchOption"
                    :default-expand="false"
                    @search="search"
                    @reset="reset" />
                <ZwTable
                    v-show="!isShowEmpty"
                    ref="tableRef"
                    :key="searchType"
                    :select-all-group="true"
                    select-all-radio
                    :option="getTableOption"
                    :row-key="getRowKey"
                    :fetch-params="state.searchParams"
                    :fetch-api="fetchApi"
                    @select="onSelect"
                    @select-all="onSelectAll"
                    @select-all-total="selectAllTotal"
                    @select-all-change="onSelectAllChange">
                    <template #headerOperate>
                        <el-button :disabled="!selectTableTotal" @click="handleExport">导出</el-button>
                    </template>
                </ZwTable>
                <el-empty v-show="isShowEmpty" description="暂无数据" />
                <display-column-config-dialog
                    v-model="columnConfigVisable"
                    :type="columnType"
                    @submit="handleSortSubmit" />
            </div>
        </div>
    </div>
</template>

<script setup lang="tsx">
import { ref, reactive, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash';

import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import {
    getGroupChatStatisticsByWorkUser,
    getGroupChatStatisticsByGroupchat,
    getGroupChatStatisticsByDate,
    exportGroupChatStatisticsByWorkUser,
    exportGroupChatStatisticsByGroupchat,
    exportGroupChatStatisticsByDate
} from '@/api/dataCenter/customerGroupAnalysis/customerGroupData';
import { getDay } from '@/utils/utils';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola.js';
import moreMenuSvg from '@/assets/dataCenter/moreMenu.svg';

import { workUserColunms, groupChatColunms, dateColunms } from './configuration/searchOption';
import {
    workUserTableColumnOption,
    groupChatTableColumnOption,
    dateTableColumnOption
} from './configuration/tableOption';
import DisplayColumnConfigDialog from './components/display-column-config-dialog.vue';

/* ----------------------------tabs栏-start---------------------------- */
/** 搜索类型 wokerUser: 按员工, groupChat: 按群聊,  date: 按日期 */
const searchType = ref<'wokerUser' | 'groupChat' | 'date'>('wokerUser');
/* ----------------------------tabs栏-end---------------------------- */

/* ----------------------------查询类型的配置项-start---------------------------- */
/**
 * 查询类型的配置项
 */
const SEARCH_TYPE_OPTION = {
    // 当前的tabs类型
    wokerUser: {
        // 表格接口
        api: getGroupChatStatisticsByWorkUser,
        // 搜索表单的列
        column: workUserColunms.value,
        // 表格的配置列
        tableOption: workUserTableColumnOption,
        // 默认值
        defaultParams: {
            work_user_ids: [],
            groupchat_role_type: 0,
            filter_time_type: 0,
            filter_time: [getDay(-7), getDay(-1, true)]
        }
    },
    groupChat: {
        api: getGroupChatStatisticsByGroupchat,
        column: groupChatColunms.value,
        tableOption: groupChatTableColumnOption,
        defaultParams: {
            owner_work_user_ids: [],
            groupchat_name: '',
            create_groupchat_time: [],
            filter_time_type: 0,
            filter_time: [getDay(-7), getDay(-1, true)]
        }
    },
    date: {
        api: getGroupChatStatisticsByDate,
        column: dateColunms.value,
        tableOption: dateTableColumnOption,
        defaultParams: {
            filter_time_type: 1,
            filter_time: []
        }
    }
};
/* ----------------------------查询类型的配置项-end---------------------------- */

/* ----------------------------搜索表格-start---------------------------- */

const isShowEmpty = ref(false);

const withMapGetApiFun = (fnApi: any) => {
    return (params: any) => {
        // eslint-disable-next-line no-async-promise-executor
        return new Promise(async (resolve, reject) => {
            try {
                const res = await fnApi(params);
                const { column, data } = res;
                // 遍历数值获取单位
                column.forEach((columnItem: any) => {
                    data.forEach((dataItem: any) => {
                        // 如果没有属性，不做操作
                        if (!dataItem.hasOwnProperty(columnItem.field_key)) {
                            return;
                        }
                        // 如果属性是number或者string类型，才叠加单位
                        if (['number', 'string'].includes(typeof dataItem[columnItem.field_key])) {
                            dataItem[columnItem.field_key] = `${dataItem[columnItem.field_key] + columnItem.unit}`;
                        }
                    });
                });
                isShowEmpty.value = false;
                resolve(res);
            } catch (err) {
                isShowEmpty.value = true;
                reject(err);
            }
        });
    };
};

/** 查询接口的api */
const fetchApi = computed(() => {
    return withMapGetApiFun(SEARCH_TYPE_OPTION[searchType.value]?.api);
});

/**
 * 切换时清掉所有的值，然后替换成默认的参数
 */
const handleTabChange = async () => {
    state.searchParams = cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams);
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
};

// 表格
const tableRef = ref<HTMLElement | any>(null);
const state = reactive({
    searchParams: cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams)
});

/** 搜索项列配置 */
const searchOption = computed(() => {
    return SEARCH_TYPE_OPTION[searchType.value]?.column;
});
const search = (v: any) => {
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();

    // 如果当前是按日期选择，处理一下日期的入参
    if (searchType.value === 'date') {
        v.filter_time_type = 0;
    } else if (v.filter_time_type === 1) {
        if (!v.filter_time?.length) {
            return ElMessage.warning('请选择统计时间');
        }
    }

    state.searchParams = { ...cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams), ...v };
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
    state.searchParams = { ...cloneDeep(SEARCH_TYPE_OPTION[searchType.value].defaultParams) };
};

const getRowKey = (row: any) => {
    return row.id;
};

/** 合并群聊配置的字段 */
const getTableOption = (columns: any[] = []) => {
    if (!columns || !columns.length) {
        return [];
    }

    const tableOption = SEARCH_TYPE_OPTION[searchType.value]?.tableOption;

    // 遍历对象找到自定义配置的信息，然后逐一合并
    const result = columns.map(columnItem => {
        if (tableOption[columnItem.field_key]) {
            Object.assign(columnItem, tableOption[columnItem.field_key]);
        }
        return {
            prop: columnItem.field_key,
            showOverflowTooltip: true,
            label: columnItem.field_name,
            ...tableOption[columnItem.field_key]
        };
    });
    return [
        {
            type: 'selection',
            width: 55,
            fixed: 'left',
            reserveSelection: true
        },
        ...result,
        {
            width: 46,
            fixed: 'right',
            label: (
                <div class="expand-header" onClick={() => handleExpandColumnsConfig()}>
                    <el-tooltip effect="dark" content="展示列设置" raw-content placement="top">
                        <img src={moreMenuSvg} />
                    </el-tooltip>
                </div>
            )
        }
    ];
};

// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
/* ----------------------------搜索表格-end---------------------------- */

/* ----------------------------展开列-start---------------------------- */
const columnConfigVisable = ref(false);
// 打开展开列弹窗
const handleExpandColumnsConfig = () => {
    columnConfigVisable.value = true;
};

/**
 * 列的type
 * 3-客户群数据按员工
 * 4-客户群数据按群聊
 * 5-客户群数据按日期
 */
const columnType = computed(() => {
    return {
        wokerUser: 3,
        // 群聊
        groupChat: 4,
        // 日期
        date: 5
    }[searchType.value];
});

const handleSortSubmit = () => {
    reloadTable();
};
/* ----------------------------展开列-end---------------------------- */

/* ----------------------------选择导出-start---------------------------- */
/** 多选选中的数量 */
const selectTableTotal = ref(0);
/**
 * 选中的数据数量
 * @param res
 */
const selectAllTotal = (value: any) => {
    selectTableTotal.value = value;
};
const onSelectAllChange = (val: any) => {
    exclude_ids.value = val;
};
const exclude_ids = ref([]);

const checkList = ref();

// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) checkList.value = selection.map(v => v.id);
};
// 全选
const onSelectAll = selection => {
    checkList.value = selection.map(v => v.id);
};

const handleExport = async (e: any) => {
    const params = {
        ...state.searchParams,
        select_type: tableRef.value?.getIsSelectAll() ? 2 : 1
    };
    // 选中的id
    const selectIds = tableRef.value?.getIsSelectAll() ? exclude_ids.value : checkList.value;

    const exportApi = {
        wokerUser: {
            // 导出的异步任务接口
            api: exportGroupChatStatisticsByWorkUser,
            // 导出的异步的选中的id字段
            key: 'export_ids'
        },
        groupChat: {
            api: exportGroupChatStatisticsByGroupchat,
            key: 'export_ids'
        },
        date: {
            api: exportGroupChatStatisticsByDate,
            key: 'group_date_ids'
        }
    }[searchType.value];

    await exportApi?.api({ ...params, [exportApi.key]: selectIds });
    parabolaAnimation(e);
    ShowTaskMessage('批量导出异步任务创建成功');
    tableRef.value?.clearSelection();
    tableRef.value?.clearAllSelect();
};
/* ----------------------------选择导出-end---------------------------- */
</script>

<style lang="scss" scoped>
@import './style/index';
</style>
